package day07;

import javax.swing.*;
import java.awt.*;

public class Demo02 {
    public static void main(String[] args) {
        JFrame f = new JFrame("弹球");
        f.setSize(300,400);
        f.setResizable(false);
        f.setLocationRelativeTo(null);
        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        MyPanel mp = new MyPanel();
        f.add(mp);
        f.setVisible(true);
        mp.move();
    }
}
class MyPanel extends JPanel {
    int x=30;
    int y=30;
    int f=0;

    @Override
    public void paint(Graphics g) {
        //清理屏幕
        g.clearRect(0,0,300,400);
        g.fillOval(x,y,20,20);
    }

    public void move(){
        while(true){
            //确定小球运动的路径
            if(f==0){
                x+=3;
                y+=3;
            }
            if(f==1){
                x-=3;
                y+=3;
            }
            if(f==2){
                x-=3;
                y-=3;
            }
            if(f==3){
                x+=3;
                y-=3;
            }
            //当达到边界条件时，如何改变小球路径
            if(x>=270){
                if(f==0){
                    f=1;
                }else{
                    f=2;
                }
            }
            if(y>=350){
                if(f==1){
                    f=2;
                }else{
                    f=3;
                }
            }
            if(x<=0){
                if(f==2){
                    f=3;
                }else{
                    f=0;
                }
            }
            if(y<=0){
                if(f==3){
                    f=0;
                }else{
                    f=1;
                }
            }
            try {
                Thread.sleep(1000/24);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
            repaint();
        }
    }
}